package com.quanquan.user.service;

import DTO.PageDTO;
import com.quanquan.user.dto.AbnormalConsumptionDTO;
import com.quanquan.user.entity.AbnormalConsumption;
import com.quanquan.user.repository.AbnormalConsumptionRepository;
import com.quanquan.user.repository.SelfHelpIntegralRepository;
import com.quanquan.user.request.AbnormalConsumptionRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import utils.DateUtils;
import utils.UUIDGenerator;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @ClassName:AbnormalConsumptionService
 * @Description:TODO
 * @Author:xiongjunbao
 * @Date:2019/8/23 17:04
 * @Version 1.0
 */
@Service
@EnableScheduling
public class AbnormalConsumptionService {

    private final AbnormalConsumptionRepository abnormalConsumptionRepository;
    private final SelfHelpIntegralRepository selfHelpIntegralRepository;

    @Autowired
    public AbnormalConsumptionService(AbnormalConsumptionRepository abnormalConsumptionRepository, SelfHelpIntegralRepository selfHelpIntegralRepository) {
        this.abnormalConsumptionRepository = abnormalConsumptionRepository;
        this.selfHelpIntegralRepository = selfHelpIntegralRepository;
    }

    /**
     * 3. 单日累计消费笔数超过8笔及以上的会员
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void findOneDayOneUserMuchDo() {
        String dateTime = DateUtils.getDate(1);
        List<Object[]> objectList = selfHelpIntegralRepository.findOneDayOneUserMuchDo(dateTime);
        for (Object[] objects : objectList) {
            AbnormalConsumption abnormalConsumption = new AbnormalConsumption();
            abnormalConsumption.setId(UUIDGenerator.getUUID());
            abnormalConsumption.setCreateTime(DateUtils.currentDate());
            abnormalConsumption.setUserId(objects[0].toString());
            abnormalConsumption.setUserName(objects[1].toString());
            abnormalConsumption.setPhone(objects[2].toString());
            abnormalConsumption.setCount(objects[3].toString());
            abnormalConsumptionRepository.saveAndFlush(abnormalConsumption);
        }

    }

    /**
     * 1. 单日单店累计消费超过4笔及以上的会员
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void findOneDayOneUserOneDo() {
        String dateTime = DateUtils.getDate(1);
        List<Object[]> objectList = selfHelpIntegralRepository.findOneDayOneUserOneDo(dateTime);
        for (Object[] objects : objectList) {
            AbnormalConsumption abnormalConsumption = new AbnormalConsumption();
            abnormalConsumption.setId(UUIDGenerator.getUUID());
            abnormalConsumption.setCreateTime(DateUtils.currentDate());
            abnormalConsumption.setUserId(objects[0].toString());
            abnormalConsumption.setUserName(objects[1].toString());
            abnormalConsumption.setPhone(objects[2].toString());
            abnormalConsumption.setStoreId(objects[3].toString());
            abnormalConsumption.setStoreName(objects[4].toString());
            abnormalConsumption.setCount(objects[5].toString());
            abnormalConsumptionRepository.saveAndFlush(abnormalConsumption);
        }
    }

    /**
     * 2. 自然周单店累计消费超过10笔及以上的会员
     */
    @Scheduled(cron = "0 0 1 ? * 1")
    public void findOneWeekOneUserOneDo() {
        String startTime = DateUtils.getDate(1);
        String endTime = DateUtils.getDate(8);
        List<Object[]> objectList = selfHelpIntegralRepository.findOneWeekOneUserOneDo(startTime, endTime);
        for (Object[] objects : objectList) {
            AbnormalConsumption abnormalConsumption = new AbnormalConsumption();
            abnormalConsumption.setId(UUIDGenerator.getUUID());
            abnormalConsumption.setCreateTime(DateUtils.currentDate());
            abnormalConsumption.setUserId(objects[0].toString());
            abnormalConsumption.setUserName(objects[1].toString());
            abnormalConsumption.setPhone(objects[2].toString());
            abnormalConsumption.setStoreId(objects[3].toString());
            abnormalConsumption.setStoreName(objects[4].toString());
            abnormalConsumption.setCount(objects[5].toString());
            abnormalConsumptionRepository.saveAndFlush(abnormalConsumption);
        }
    }


    /**
     * 后台查看异常消费数据
     *
     * @return
     */
    public PageDTO<AbnormalConsumptionDTO> queryMenegement(AbnormalConsumptionRequest requestBody) {
        Integer page = null == requestBody.getPage() ? 0 : requestBody.getPage();
        Integer size = null == requestBody.getSize() ? 10 : requestBody.getSize();
        boolean asc = requestBody.isAsc();
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        String keyword = requestBody.getKeyword();
        String fromDate = requestBody.getFromDate();
        String toDate = requestBody.getToDate();
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<AbnormalConsumption> paged = abnormalConsumptionRepository.findAll((Specification<AbnormalConsumption>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            // 创建具体查询条件
            if (StringUtils.isNotEmpty(fromDate)) {
                Date from = DateUtils.strToDate(fromDate, DateUtils.DATE);
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime").as(Date.class), from));
            }
            if (StringUtils.isNotEmpty(toDate)) {
                Date to = DateUtils.getEndOfDay(DateUtils.strToDate(toDate, DateUtils.DATE));
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime").as(Date.class), to));
            }
            if (StringUtils.isNotEmpty(keyword)) {
                Predicate p1 = criteriaBuilder.like(root.get("phone").as(String.class), "%" + keyword + "%");
                Predicate p2 = criteriaBuilder.or(criteriaBuilder.like(root.get("userName").as(String.class), "%" + keyword + "%"), p1);
                Predicate p3 = criteriaBuilder.or(criteriaBuilder.like(root.get("storeName").as(String.class), "%" + keyword + "%"), p2);
                predicates.add(p3);
            }
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        }, pageable);
        List<AbnormalConsumption> content = paged.getContent();
        List<AbnormalConsumptionDTO> abnormalConsumptionDTOS = new LinkedList<>();
        for (AbnormalConsumption abnormalConsumption : content){
            AbnormalConsumptionDTO abnormalConsumptionDTO = new AbnormalConsumptionDTO();
            BeanUtils.copyProperties(abnormalConsumption,abnormalConsumptionDTO);
            abnormalConsumptionDTOS.add(abnormalConsumptionDTO);
        }
        PageDTO<AbnormalConsumptionDTO> dto = new PageDTO<>();
        dto.setTotal(paged.getTotalElements());
        dto.setAsc(asc);
        dto.setKeyword(requestBody.getKeyword());
        dto.setFromDate(fromDate);
        dto.setToDate(toDate);
        dto.setList(abnormalConsumptionDTOS);
        dto.setPage(page);
        dto.setPageSize(size);
        dto.setTotalPage(paged.getTotalPages());
        return dto;
    }


}
